// 系统信息管理页面
import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore.js';
import { Card, Form, Input, Select, Button, DatePicker, notification, Alert } from "antd";
import dayjs from 'dayjs';
import request from '../../untils/request.js';

const Info = () => {
  const [form] = Form.useForm();
  const [systemInfo, setSystemInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const status = Form.useWatch('status', form);
  const { collapsed } = useStore();

  // 系统状态选项
  const statusOptions = [
    { value: 0, label: "停运" },
    { value: 1, label: "正常运行" }
  ];

  // 格式化内存大小（字节转GB）
  const formatMemory = (bytes) => 
    (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';

  // 获取系统信息
  useEffect(() => {
    request("/admin/sys/getSysInfo")
    .then(data => {
      setSystemInfo(data);
      form.setFieldsValue({
        name: data.name,
        company_name: data.company_name,
        status: data.status,
        version: data.version,
        open_time: dayjs(data.open_time)
      });
    })
    .catch(() => {
      notification.error({
        message: "获取数据失败",
        description: "无法加载系统信息，请刷新页面重试"
      });
    })
    .finally(() => {
      setLoading(false); // 无论成功失败都关闭加载状态
    });
  }, []);

  // 提交系统信息修改
  const handleSubmit = () => {
    const formData = form.getFieldValue();
    const submitData = {
      ...formData,
      id: systemInfo?.id,
      open_time: dayjs(formData.open_time).format("YYYY-MM-DD HH:mm:ss")
    };

    request("/admin/sys/updateSysInfo", {
      method: 'POST',
      body: submitData // 直接传入对象，工具会自动处理JSON序列化
    })
    .then(data => {
      notification[data.code === 200 ? 'success' : 'error']({
        message: data.msg
      });
    })
    .catch(() => {
      notification.error({
        message: "更新失败",
        description: "无法更新系统信息，请稍后重试"
      });
    });
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        加载中...
      </div>
    );
  }

  return (
    <div style={{
      height: "94%",
      backgroundColor: "#F1F1F1",
      right: "1%",
      top: "4vh",
      overflow: "auto",
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      color: "white",
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          width: "99%",
          backgroundColor: "white",
          margin: "0.5vw",
          padding: "1vw",
          color: "black"
        }}>
          <Card 
            style={{ width: '100%', marginTop: "2vh" }} 
            title="系统信息管理"
          >
            {/* 系统基本信息 */}
            <div style={styles.infoCard}>
              <h3 style={styles.sectionTitle}>系统基本信息</h3>
              <div style={styles.infoGrid}>
                <div><span style={styles.label}>系统ID: </span>{systemInfo?.id || 'N/A'}</div>
                <div><span style={styles.label}>版本号: </span>{systemInfo?.version || 'N/A'}</div>
                <div>
                  <span style={styles.label}>系统状态: </span>
                  <span style={{ 
                    fontWeight: '500', 
                    color: status === 1 ? '#52c41a' : '#f5222d' 
                  }}>
                    {status === 1 ? "正常运行" : "停运"}
                  </span>
                </div>
                {/* 仅在系统停运时显示最近开放时间 */}
                {status === 0 && (
                  <div>
                    <span style={styles.label}>最近开放时间: </span>
                    {systemInfo?.open_time || 'N/A'}
                  </div>
                )}
              </div>
            </div>

            {/* 内存信息展示 */}
            {systemInfo?.memory && (
              <div style={styles.infoCard}>
                <h3 style={styles.sectionTitle}>系统资源信息</h3>
                
                {/* 内存使用率进度条 */}
                <div style={styles.progressContainer}>
                  <div style={styles.progressHeader}>
                    <span style={styles.label}>内存使用率</span>
                    <span>{systemInfo.memory.usage}%</span>
                  </div>
                  <div style={styles.progressBarBg}>
                    <div 
                      style={{ 
                        ...styles.progressBar,
                        width: `${systemInfo.memory.usage}%`, 
                        backgroundColor: systemInfo.memory.usage > 80 ? '#faad14' : '#52c41a'
                      }}
                    ></div>
                  </div>
                </div>
                
                {/* 内存详细信息 */}
                <div style={styles.infoGrid}>
                  <div><span style={styles.label}>总内存: </span>{formatMemory(systemInfo.memory.total)}</div>
                  <div><span style={styles.label}>已使用内存: </span>{formatMemory(systemInfo.memory.used)}</div>
                  <div><span style={styles.label}>空闲内存: </span>{formatMemory(systemInfo.memory.free)}</div>
                </div>
              </div>
            )}

            {/* 编辑表单 */}
            <Card title="系统信息编辑">
              <Form form={form} layout="vertical">
                <Form.Item
                  label="系统名称"
                  name="name"
                  rules={[{ required: true, message: '系统名称不能为空' }]}
                >
                  <Input maxLength={50} showCount />
                </Form.Item>
                
                <Form.Item
                  label="公司名称"
                  name="company_name"
                  rules={[{ required: true, message: '公司名称不能为空' }]}
                >
                  <Input maxLength={50} showCount />
                </Form.Item>
                
                <Form.Item
                  label="版本号"
                  name="version"
                  rules={[{ required: true, message: '版本号不能为空' }]}
                >
                  <Input maxLength={20} showCount />
                </Form.Item>
                
                <Form.Item label="系统状态" name="status">
                  <Select options={statusOptions} />
                </Form.Item>
                
                <Form.Item
                  label="重新开放时间"
                  name="open_time"
                  style={{ display: status === 0 ? 'block' : 'none' }}
                  rules={[{ required: status === 0, message: '请选择重新开放时间' }]}
                >
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                </Form.Item>
                
                {status === 0 && (
                  <Alert 
                    style={{ marginBottom: 16 }} 
                    message="重新开放时间仅作参考，实际开放需管理员完成运维后，手动登入系统重新开放！（停运期间，超级管理员仍然可以登入系统）" 
                    type="warning" 
                  />
                )}
                
                <Form.Item>
                  <Button onClick={handleSubmit} type="primary" danger>提交修改</Button>
                </Form.Item>
              </Form>
            </Card>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default Info;

// 样式集中管理
const styles = {
  kshcontainer: {
    width: "100%",
    minHeight: "40vh",
    position: "absolute",
    top: "2vh",
    left: "0vw",
    backgroundColor: "#F1F1F1",
    color: "black"
  },
  infoCard: {
    marginBottom: 20,
    border: '1px solid #eee',
    padding: '15px',
    borderRadius: '4px'
  },
  sectionTitle: {
    margin: '0 0 15px 0',
    color: '#1890ff',
    fontSize: '16px'
  },
  infoGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
    gap: '10px'
  },
  label: {
    color: '#666',
    fontSize: '14px'
  },
  progressContainer: {
    marginBottom: 15
  },
  progressHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    marginBottom: 5
  },
  progressBarBg: {
    height: '8px',
    width: '100%',
    backgroundColor: '#e8e8e8',
    borderRadius: '4px',
    overflow: 'hidden'
  },
  progressBar: {
    height: '100%',
    borderRadius: '4px'
  }
};
